#############################################################################
# Copyright (c) 2009 Dmitry Grushin <dgrushin@gmail.com>.
#
# This file is part of clupower (cluster power manager utility)
#
# Clupower is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Clupower is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Clupower.  If not, see <http://www.gnu.org/licenses/>.
#
# Contributors:
#    Dmitry Grushin <dgrushin@gmail.com> - initial API and implementation
#############################################################################

#
# Starts cluster node using ipmi telnet connection.
# Node name is appended with -ipmi suffix.
#
require 'net/telnet'
require 'header'
require 'commands'

def usage
  puts HEADER
  puts "Usage: #{$0} [all] [node-id, ...]"
  puts "This program will connect to the cluster node through the telnet" +
    " interface and try to switch it on."
  puts "Note: node ids will be appended with \"-ipmi\". Check your /etc/hosts file."
  puts " all: switch on all cluster nodes listed in pbsnodes output."
end

def node_up(node)
  s = Net::Telnet.new(
    "Host" => node,
    "Timeout" => 10
  )
  s.login(Settings.instance.get('CMD_IPMITOOL_LOGIN'),
    Settings.instance.get('CMD_IPMITOOL_PASSWORD'))
  s.cmd("cd system1")
  output = s.cmd("start")
  s.close
  unless output.include?("System1 started.")
    puts "IPMI command failed."
    exit(1)
  end
  puts "Node #{node} started."
  Cmd.instance.torque_node_online(node)
rescue CPRuntimeError => e
  puts "Unable to clear offline status from node #{node}"
rescue Exception => e
  puts "Unable to wake up node #{node}: #{e.message}"
end

if ARGV.size == 0 then
  usage
else
  if ARGV[0] == "all"
    if ARGV.size != 1
      usage
    else
      Cmd.instance.get_down_nodes.each do |node|
        node_up(Cmd.instance.ipmi_node_name(node))
      end
    end
  else
    ARGV.each { |node| node_up(Cmd.instance.ipmi_node_name(ARGV[0])) }
  end
end
